package com.cangshi.service;

import com.cangshi.dao.UserMapper;
import com.cangshi.entity.User;
import com.cangshi.exception.JsonException;
import com.cangshi.shiro.ssesion.OnlineSessionManager;
import com.cangshi.utils.MD5Tools;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Eoly on 2017/6/5.
 */
@Service("userBean")
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    private OnlineSessionManager onlineSessionManager;

    @Override
    public User getUserByLoginName(String loginName) {

        if (loginName.contains("%")) {
            loginName = loginName.replaceAll("%", "\\\\%");
        }

        if (loginName.contains("_")) {
            loginName = loginName.replaceAll("_", "\\\\_");
        }

        User user = new User();
        user.setUserLogin(loginName);

        List<User> users = userMapper.selectUsers(null, null, user);

        return users.get(0);
    }

    @Override
    public User login(String username, String password) {

        if (username == null || password == null) {
            throw new JsonException("未接收到登录信息", 405);
        }

        if (username.contains("%")) {
            username = username.replaceAll("%", "\\\\%");
        }

        if (username.contains("_")) {
            username = username.replaceAll("_", "\\\\_");
        }

        User user = new User();
        user.setUserLogin(username);
        user.setUserPass(password);
        user.setUserPass(MD5Tools.MD5(user.getUserPass()));

        List<User> users = userMapper.selectUsers(null, null, user);

        if (users.size() == 0) {
            throw new JsonException("用户登录名或密码错误", 405);
        }

        User userLogin = users.get(0);
        if (userLogin.getUserPower() != 2) {
            throw new JsonException("用户权限不足", 405);
        }

        return userLogin;
    }

    @Override
    public Boolean logout() {

        return null;
    }

    @Override
    public List<User> getUsersLimited(Integer offset, Integer userSize) {
        return userMapper.selectUsers(offset, userSize, null);
    }

    @Override
    public Boolean deleteUserById(Integer id) {
        Integer result = userMapper.deleteByPrimaryKey(id);
        return result == 1;
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public Boolean changePassword(Integer id, String newPassword) {
        User user = new User();
        user.setUserId(id);
        user.setUserPass(MD5Tools.MD5(newPassword));
        Integer result = userMapper.updateByPrimaryKeySelective(user);
        return result == 1;
    }

    @Override
    public Boolean editUserBaseInfo(User user) {
        if (user.getUserId() == null) {
            throw new JsonException("用户id为空，无法修改", 405);
        }
        User userEdit = new User();
        userEdit.setUserId(user.getUserId());
        userEdit.setUserDisplay(user.getUserDisplay());
        userEdit.setUserBirthday(user.getUserBirthday());
        userEdit.setUserSex(user.getUserSex());
        userEdit.setUserAvatar(user.getUserAvatar());
        userEdit.setUserDetail(user.getUserDetail());
        Integer result = userMapper.updateByPrimaryKeySelective(userEdit);
        return result == 1;
    }

    @Override
    public Boolean editUserStatus(User user) {
        if (user.getUserId() == null) {
            throw new JsonException("用户id为空，无法修改", 405);
        }
        User userEdit = new User();
        userEdit.setUserId(user.getUserId());
        userEdit.setUserStatus(user.getUserStatus());
        userEdit.setUserPower(user.getUserPower());
        Integer result = userMapper.updateByPrimaryKeySelective(userEdit);
        return result == 1;
    }

    @Override
    public Boolean addUser(User user) {
        user.setUserPass(MD5Tools.MD5(user.getUserPass()));
        Integer result = userMapper.insertSelective(user);
        if (result != 1) {
            throw new RuntimeException("用户注册失败");
        }
        return Boolean.TRUE;
    }

    @Override
    public Integer getUserVolume() {
        return userMapper.selectCount(null);
    }

    @Override
    public Integer getUserVolumeWithKeywords(String keywords) {
        User user = null;
        if (keywords != null) {
            user = new User();
            user.setUserDisplay("%" + keywords + "%");
        }
        return userMapper.selectCount(user);
    }

    @Override
    public List<User> getUsersWithKeywords(Integer offset, Integer userSize, String keywords) {
        User user = null;
        if (keywords != null) {
            user = new User();
            user.setUserDisplay("%" + keywords + "%");
        }
        return userMapper.selectUsers(offset, userSize, user);
    }

    @Override
    public PageInfo<User> getUsersByPageWithKeywords(Integer pageNumber, Integer pageSize, String keywords) {
        PageHelper.startPage(pageNumber, pageSize);
        User user = null;
        if (keywords != null) {
            user = new User();
            user.setUserDisplay("%" + keywords + "%");
        }
        List<User> users = userMapper.selectUsers(null, null, user);
        return new PageInfo<User>(users);
    }

    @Override
    public Map<Serializable, User> getOnlineUsersWithKeywords(Integer offset, Integer userSize, String keywords) {
        int count = 0;
        Map<Serializable, Session> sessionList = onlineSessionManager.getSessionsOnline();
        Map<Serializable, User> usersLogin = new LinkedHashMap<Serializable, User>();
        for (Serializable id : sessionList.keySet()) {
            User user = (User) sessionList.get(id).getAttribute("userLogin");
            if (keywords == null || user.getUserDisplay().contains(keywords)) {
                count++;
                if (offset == null || userSize == null || count > offset) {
                    usersLogin.put(id, user);
                }
                if (offset != null && userSize != null && count >= offset + userSize) {
                    break;
                }
            }
        }
        return usersLogin;
    }

    @Override
    public Integer getOnlineUserNum(String keywords) {
        Map<Serializable, Session> sessionList = onlineSessionManager.getSessionsOnline();
        if (keywords == null) {
            return sessionList.size();
        }
        Integer count = 0;
        for (Serializable id : sessionList.keySet()) {
            User user = (User) sessionList.get(id).getAttribute("userLogin");
            if (user.getUserDisplay().contains(keywords)) {
                count++;
            }
        }
        return count;
    }

}
